﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using System.Xml;
using MySql.Data;
using MySql.Data.MySqlClient;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TaskbarClock;

namespace PositionMeasureSystem
{
    public partial class Form1 : Form
    {
        /*public struct LocSize
        {
            public int x, y,dx,dy;
        }*/
        
        static public string gEnvironment = Environment.CurrentDirectory;
        static public bool IsSaveFlag = false;
        static public bool flagRun = false;
        static public string xmlPath = gEnvironment + "\\UserPrj";
        static public string sensorSetXml = xmlPath + "\\SensorSetting.Xml";
        static public string gProjectPath;
        static public int intWpID = 1;
        static public string data = DateTime.Now.ToString("yyMMdd");
        static public string strWpID = data + "0001";
        public long samplingTime;
        public DateTime StartTime;
        public XmlDocument gProjectDoc;
        XmlDocument SensorSetting = new XmlDocument();
        //public MonitorControl monitorControl=new MonitorControl();
        PosSensor_DLEN1 DlEn1 = new PosSensor_DLEN1();
        public SensorSetting sensorSetting;
        public List<FigPanel> FigPanelsForTop = new List<FigPanel>();
        public List<List<float>> floatMeasureData;
        public List<List<float>> floatCalculData;
        


        public Form1 ()
        {
            InitializeComponent();
            splitContainer4.SplitterDistance = splitContainer4.Width / 2;
            XmlProjInit();
            tabControl1.SelectedTab = tabControl1.TabPages[1];

        }
        public int gFormSizeWidth = 0;
        public int gFormSizeHeight = 0;
        
        private void Form1_Load (object sender, EventArgs e)
        {
            int dpi = this.DeviceDpi;
            gFormSizeWidth = this.Size.Width;
            gFormSizeHeight = this.Size.Height;
            GetInitFormSize();
            bt_measure.Enabled = false;
            bt_stop.Enabled = false;
            ctxtMenStrip.Items[0].Enabled = false;//刷新
            ctxtMenStrip.Items[1].Enabled = false;//测量
            ctxtMenStrip.Items[2].Enabled = false;//暂停
            ctxtMenStrip.Items[3].Enabled = false;//停止
            ctxtMenStrip.Items[4].Enabled = true;//保存
            ckBox_Save.Enabled = true;
            cBox_fre.Text = Convert.ToString(floatSensorState[0][1]);

            tb_wpID.Text = uint.Parse(strWpID) > uint.Parse(strProjectInfo[4]) ? strWpID : strProjectInfo[4];
            //strProjectInfo[4] = tb_wpID.Text;
            /*tb_wpID.Text = strWpID;*/
            /*statusStrip2= statusStrip1;
            checkBox2.Parent = statusStrip2;*/
        }    
        #region 窗口自适应调整
        private float gScalX = 1;
        private float gScalY = 1;
        private float gScalFont = 1;
        private int FullW0 = 1920;
        private int FullH0 = 1080;
        private int CurW;
        private int CurH;

        int CtrlAdjEn = 0;
        private void Form1_Shown (object sender, EventArgs e)
        {
            AutoScalMyWindow();
            CtrlAdjEn = 1;
            //this.WindowState = FormWindowState.Maximized;
        }
        public void AutoSetCrlState(Control CrlContainer,int top)//重新设定窗体中各控件的状态（在与原状态的对比中计算而来）
        {
            try
            {
                Font font;
                if (this.WindowState == FormWindowState.Maximized)
                    return;
                if (top != 0)
                {
                    gScalX = (float)this.Width / CurW;
                    gScalY = (float)this.Height / CurH;
                    gScalFont=(gScalX<gScalY)?gScalX:gScalY;
                    CurW = this.Width;
                    CurH = this.Height;
                }
                foreach(Control kCrl in CrlContainer.Controls)
                {
                    Point point = new Point();//位置修改
                    point.X = Convert.ToInt32(gScalX*kCrl.Location.X);
                    point.Y = Convert.ToInt32(gScalY*kCrl.Location.Y);

                    kCrl.Location = point;

                    float fontsize=gScalFont*kCrl.Font.Size;
                    font = new System.Drawing.Font("宋体", fontsize, kCrl.Font.Style);
                    
                    if(fontsize < 24 && fontsize > 12) kCrl.Font = font;
                    kCrl.Enabled = true;
                    
                    if (kCrl.Controls.Count > 0)
                    {
                        AutoSetCrlState(kCrl, 0);
                    }
                }
                this.Refresh();
                return;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }
        private void AutoScalMyWindow ()
        {
            //AutoHeightAdj(splitContainer3.Panel1, 0);
            //AutoHeightAdj(splitContainer2.Panel2,0); 
            //AutoHeightAdj(sensorSetting, 0);
            //AutoWidthAdj(splitContainer3, 0);
            
            //AutoWidthAdj(splitContainer3.Panel1, 0);
            //AutoWidthAdj(splitContainer3.Panel2, 0);
        }
        private void Form1_Resize (object sender, EventArgs e)
        {
            if (CtrlAdjEn == 0)
            {
                return;
            }
            CtrlAdjEn = 1;
            //AutoSetCrlState(this, 1);
            AutoScalMyWindow();
        }
            
        public void GetInitFormSize ()//获得并存储窗体的初始尺寸
        {
            CurW = this.Size.Width;
            CurH = this.Size.Height;
            gScalX = (float)CurW / FullW0;
            gScalY = (float)CurH / FullH0;
            gScalFont = (gScalX < gScalY) ? gScalX : gScalY;
        }
        #endregion

        #region 载入XML文件
        static public List<List<float>> floatSensorState;//index,measureFre,zeroValue
        static public List<List<string>> strSensorState;//sensorName,MeasureName,measureTyprStr
        static public List<string> strProjectInfo;
        public void XmlProjInit ()
        {
            string roomTempre = tb_roomTempre.Text;
            string wpTempre = tb_wpTempre.Text;
            SensorSetting.Load(sensorSetXml);
            XmlElement xmlnode = SensorSetting.DocumentElement;
            this.treeView_Sensor.Nodes.Add(xmlnode.SelectSingleNode("Project").InnerText);
            XmlNodeList xmlNodeList = xmlnode.SelectNodes("//SensorName");
            foreach (XmlNode node in xmlNodeList)
            {
                this.treeView_Sensor.Nodes[0].Nodes.Add(node.InnerText);
               
            }
            this.treeView_Sensor.ExpandAll();
            floatSensorState = new List<List<float>>();
            strSensorState = new List<List<string>>();
            strProjectInfo = new List<string>();
            floatMeasureData = new List<List<float>>();
            floatCalculData = new List<List<float>>();
            int sensorNum = Convert.ToInt32(xmlnode.SelectSingleNode("SensorNum").InnerText);
            string project = xmlnode.SelectSingleNode("Project").InnerText;
            string item = xmlnode.SelectSingleNode("Item").InnerText;
            string wpIDxml = xmlnode.SelectSingleNode("WpID").InnerText;
            strProjectInfo.Add(project);
            strProjectInfo.Add(item);
            strProjectInfo.Add(roomTempre);
            strProjectInfo.Add(wpTempre);
            strProjectInfo.Add(wpIDxml);

            XmlNode rootNode = xmlnode.SelectSingleNode("Sensors");
            XmlNodeList sensorXml = rootNode.ChildNodes;

            foreach (XmlNode node in sensorXml)
            {
                string measureResult = null;
                string measureGrade = null;
                
                floatMeasureData.Add(new List<float>());
                floatCalculData.Add(new List<float>());
                XmlNode index_Xml = node.ChildNodes[1];
                XmlNode measureName_Xml = node.ChildNodes[2];
                XmlNode measureType_Xml = node.ChildNodes[3];
                strSensorState.Add(new List<string>());
                XmlNode sensorName_Xml = node.FirstChild;
                string sensorName = sensorName_Xml.InnerText;
                strSensorState[strSensorState.Count - 1].Add(sensorName);//strSensorState[i][0]
                int index = Convert.ToInt32(index_Xml.InnerText);
                string measureName = measureName_Xml.InnerText;
                strSensorState[strSensorState.Count - 1].Add(measureName);//strSensorState[i][1]
                string measureTypeStr= measureType_Xml.InnerText;
                strSensorState[strSensorState.Count - 1].Add(measureTypeStr);//strSensorState[i][2]
                strSensorState[strSensorState.Count - 1].Add(measureResult);//strSensorState[i][3]
                strSensorState[strSensorState.Count - 1].Add(measureGrade);//strSensorState[i][4]
                XmlNode measureFreq_Xml = node.ChildNodes[4];
                int measureFre = Convert.ToInt32(measureFreq_Xml.InnerText);
                XmlNode zeroValue_Xml = node.ChildNodes[5];
                float zeroValue = float.Parse(zeroValue_Xml.InnerText);
                XmlNode tolerance_Xml= node.ChildNodes[6];
                float tolerance = float.Parse(tolerance_Xml.InnerText);             
                floatSensorState.Add(new List<float>());
                floatSensorState[floatSensorState.Count - 1].Add(index);//floatSensorState[i][0]
                floatSensorState[floatSensorState.Count - 1].Add(measureFre);//floatSensorState[i][1]
                floatSensorState[floatSensorState.Count - 1].Add(zeroValue);//floatSensorState[i][2]
                floatSensorState[floatSensorState.Count - 1].Add(tolerance);//floatSensorState[i][3]            
            }
            
        }
        private void ModifyXmlInformation (string xmlFilepath)
        {
            try
            {
                XmlDocument myXmlDoc = new XmlDocument();
                myXmlDoc.Load(xmlFilepath);
                XmlNode rootNode = myXmlDoc.SelectSingleNode("SensorSetting");
                XmlNodeList xmlNodeList = rootNode.ChildNodes;
                
                xmlNodeList[5].InnerText = Form1.strProjectInfo[4];
                 myXmlDoc.Save(xmlFilepath);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        #endregion

        public void ChartTop ()
        {
            if (splitContainer5.Panel1.Controls.Count == 0)
            {
                gProjectPath = xmlPath + "\\XMLProjectTop.xml";
                gProjectDoc = new XmlDocument();
                gProjectDoc.Load(gProjectPath);
                XmlNode root = gProjectDoc.SelectSingleNode("//root");
                XmlNode monitorroot = root.SelectSingleNode("//MonitorRoot");
                if (monitorroot == null)
                    return;
                XmlNodeList monitors = monitorroot.ChildNodes;
                foreach (XmlNode monitor in monitors)
                {
                    if (monitor.Name == "Monitor")   //限制了窗体的节点只能用"Monitor"
                    {
                        FigPanel figPanel = new FigPanel(monitor);
                        figPanel.Parent = splitContainer5.Panel1;
                        FigPanelsForTop.Add(figPanel);
                        splitContainer5.Panel1.Controls.Add(figPanel.mPanel);
                        figPanel.mPanel.Dock = DockStyle.Fill;
                        FigPanel.CreatFigsTop(monitor, ref figPanel);
                    }
                }
            }           
        }
        public void ChartBottom ()
        {
            if (splitContainer5.Panel2.Controls.Count == 0)
            {
                gProjectPath = xmlPath + "\\XMLProjectBottom.xml";
                gProjectDoc = new XmlDocument();
                gProjectDoc.Load(gProjectPath);
                XmlNode root = gProjectDoc.SelectSingleNode("//root");
                XmlNode monitorroot = root.SelectSingleNode("//MonitorRoot");
                if (monitorroot == null)
                    return;

                
                XmlNodeList monitors = monitorroot.ChildNodes;
                foreach (XmlNode monitor in monitors)
                {
                    if (monitor.Name == "Monitor")   //限制了窗体的节点只能用"Monitor"
                    {
                        
                        FigPanel figPanel = new FigPanel(monitor);
                        figPanel.Parent = splitContainer5.Panel2;
                        //FigPanels.Add(figPanel);
                        splitContainer5.Panel2.Controls.Add(figPanel.mPanel);
                        figPanel.mPanel.Dock = DockStyle.Fill;
                        FigPanel.CreatFigsBot(monitor, ref figPanel);
                    }
                }
            }
        } 
        #region 连接
        public string IP;
        public string Port;
        private void bt_connect_Click (object sender, EventArgs e)
        {
            
            testTimer.Stop();
            IP = textBox_IP.Text;
            Port = textBox_Port.Text;
            if (statusConnect.Text != "已连接")
            {
                if (IP == "")
                {
                    try { IP = "192.168.0.3"; }
                    catch (Exception ex) { MessageBox.Show("IP设置错误"); }
                }
                int port = 64000;

                if (Port != "")
                {
                    try { port = int.Parse(Port); }
                    catch (Exception ex) { MessageBox.Show("端口号设置错误"); }
                }
                if (DlEn1.PortInit(textBox_IP.Text, port) < 0)
                    return;

                if (DlEn1.TotalSensors > 0)
                {

                    statusConnect.Text = "已连接";
                    statusConnect.BackColor = Color.Green;
                    bt_connect.Enabled = false;
                    dataGridView1Init();
                    bt_measure.Enabled = true;
                    bt_measure.Text = "测量";
                    ctxtMenStrip.Items[1].Enabled = true;//测量
                    ctxtMenStrip.Items[1].Text = "测量";


                }
            }
            ConnectMysql();
        }
        private void dataGridView1Init ()
        {
            if (DlEn1.TotalSensors < 1)
                return;

            for (int i = 0; i < DlEn1.TotalSensors; i++)
            {
                dataGridView1.Rows.Add();
                dataGridView1.Rows[i].Cells[0].Value = strSensorState[i][0];
            }
        }         
        static public string strSelNode;
        //点选传感器树以进行设置
        private void treeView_Sensor_AfterSelect (object sender, TreeViewEventArgs e)
        {
            TreeNode selNode = treeView_Sensor.SelectedNode;
            strSelNode = selNode.Text;
            if (strSelNode != strProjectInfo[0])
            {
                if (splitContainer3.Panel2 != null)
                {
                    splitContainer3.Panel2.Controls.Clear();
                }
                sensorSetting = new SensorSetting();
                sensorSetting.Parent = splitContainer3.Panel2;
                sensorSetting.label1.Text = "设置" + selNode.Text;
            }
        }
        #endregion
       
        #region 采集
        private void bt_measure_Click (object sender, EventArgs e)
        {
            if (IsSaveFlag)
            {
                CreatTxtFile();
                SaveData(dataPath);
                CreatTable(strProjectInfo[4]);
            }
            
            ChartTop();
            ChartBottom();
            PosTimer.Interval = 1000 / int.Parse(cBox_fre.Text);
            StartTime = DateTime.Now;
            
            PosTimer.Start();
            tabControl1.SelectedTab = tabControl1.TabPages[0];
            bt_measure.Enabled = false;
            bt_stop.Enabled = true;
            ctxtMenStrip.Items[0].Enabled = true;
            ctxtMenStrip.Items[1].Enabled = false;
            ctxtMenStrip.Items[2].Enabled = true;
            ctxtMenStrip.Items[3].Enabled = true;
            ckBox_Save.Enabled = false;
            ctxtMenStrip.Items[4].Enabled = false;
        }
        
        static string dataPath;
        static string current_time;
        void CreatTxtFile ()
        {
            string current_day = DateTime.Now.ToString("MM_dd");
            string current_month = DateTime.Now.ToString("MM");
            string current_year = DateTime.Now.Year.ToString();
            current_time = DateTime.Now.ToString("HH_mm_ss");
            string txtName = current_time + "_" + strProjectInfo[4];
            string year_Path = xmlPath + "\\MeasureData" + "\\"+current_year;
            if(!Directory.Exists(year_Path))
            {
                Directory.CreateDirectory(year_Path);
            }
            string month_Path=year_Path+ "\\" + current_month;
            if(!Directory.Exists(month_Path))
            {
                Directory.CreateDirectory(month_Path);
            }
            string day_Path=month_Path+ "\\" + current_day;
            if (!Directory.Exists(day_Path))
            {
                Directory.CreateDirectory(day_Path);
            }
            string txtPath = day_Path + "\\" + txtName + ".txt";
            if(!File.Exists(txtPath))
            {
                FileStream fs1=new FileStream(txtPath, FileMode.Create);
                fs1.Close();
            }
            dataPath = txtPath;
            
        }
        private void bt_suspendMeasure_Click (object sender, EventArgs e)
        {

        }
        private void bt_stop_Click (object sender, EventArgs e)
        {
            stopMeasure_Click(sender, e);
            ctxtMenStrip.Items[1].Enabled = true;
            ctxtMenStrip.Items[2].Enabled = false;
        }
        static string str = null;
        static bool IsWriteFlag = false;
        static bool IsReadFlag = false;
        private void PosTimer_Tick (object sender, EventArgs e)
        {
            //string str = null;

            if (DlEn1.DLEN1Client.Connected == false)
                return;
            int len = DlEn1.GetM0Data();
            DateTime time = DateTime.Now;
            //string str = time.ToString("yyyy:MM:dd:HH:mm:ss");
            //samplingTime = (uint)((time.Ticks - StartTime.Ticks) / 100000);
            samplingTime = (long)time.Ticks - StartTime.Ticks;
            if (len < 0)
            {
                statusConnect.Text = "未连接";
                statusConnect.BackColor = Color.Gray;
                DlEn1.ConnectReset();
                PosTimer.Stop();
                MessageBox.Show("传感器网络断开，请从新连接");
                return;
            }
            if (len > 0)
            {
                
                
                str = samplingTime.ToString();
                for (int i = 0; i < DlEn1.TotalSensors; i++)
                {
                    
                    if (DlEn1.Sensor[i].aPos < 0)
                    {
                        dataGridView1.Rows[i].Cells[1].Value = DlEn1.Sensor[i].aPos.ToString("0.0000");
                    }
                    else
                    {
                        dataGridView1.Rows[i].Cells[1].Value = " " + DlEn1.Sensor[i].aPos.ToString("0.0000");
                    }
                    float rPos = DlEn1.Sensor[i].aPos - floatSensorState[i][2];
                    if (rPos < 0)
                    {
                        dataGridView1.Rows[i].Cells[2].Value = rPos.ToString("0.0000");
                    }
                    else
                    {
                        dataGridView1.Rows[i].Cells[2].Value = " " + rPos.ToString("0.0000");
                    }
                    //FigPanel.ChartBot.Series[i].Points.AddXY(k, DlEn1.Sensor[i].aPos);
                    if (Math.Abs(rPos) <0.25)//相对值小于0.25才会加入计算数组
                    {
                        floatCalculData[i].Add(rPos);
                    }


                    FigPanel.ChartBot.Series[i].Points.AddY(rPos);
                    FigPanelsForTop[0].Charts[i].Series[0].Points.AddY(rPos);
                    floatMeasureData[i].Add(rPos);
                    FigPanelsForTop[0].Charts[i].Titles[0].Font = new Font("微软雅黑",22f);
                    FigPanelsForTop[0].Charts[i].Titles[0].Text = strSensorState[i][0]
                        + "\r\n"
                        + strSensorState[i][2] + ":" + rPos.ToString("0.0000") + "mm"
                        + "\r\n"
                        + "  测量结果:" + MeasureResult(i) + "mm"
                        + "\r\n"
                        + "合格:"+Grade(i);
                    strSensorState[i][3] = MeasureResult(i);
                    str += "\t" + DlEn1.Sensor[i].aPos.ToString("0.0000");                     
                }
            }
            if (IsSaveFlag)
            {

                string infor = "工件编号：" + "\t" + strProjectInfo[4];
                string infor0  = "工件名称：" + "\t" + strProjectInfo[1];
                string infor1 = "环境温度(℃)：" + "\t" + strProjectInfo[2];
                string infor2 = "工件温度(℃)：" + "\t" + strProjectInfo[3];
                string infor3 = "时间戳：";
                string infor4 = "测量结果：";
                string infor5 = "  合格：";
                string infor6 = "工件公差：";
                string infor7 = "传感器零点：";
                
                StreamWriter sw = new StreamWriter(dataPath, true);
                if (!IsWriteFlag)
                {
                    for(int i = 0; i < DlEn1.TotalSensors; i++)
                    {
                        infor3 += "\t" + strSensorState[i][1];
                        infor6 += "\t" + floatSensorState[i][3].ToString("0.0000");
                        infor7 += "\t" + floatSensorState[i][2].ToString("0.0000");
                    }
                    sw.WriteLine(infor);
                    sw.WriteLine(infor0);
                    sw.WriteLine(infor1);
                    sw.WriteLine(infor2);
                    sw.WriteLine(infor3);
                    sw.WriteLine(infor4);
                    sw.WriteLine(infor5);
                    sw.WriteLine(infor6);
                    sw.WriteLine(infor7);
                    IsWriteFlag= true;
                }
                sw.WriteLine(str);
                sw.Close();

                string[] strings = str.Split('\t');
                string sql = "insert into demo." + strProjectInfo[4] + "(timestp, sensor1,sensor2,sensor3,sensor4) " +
                 "values(?timestp,?sensor1,?sensor2,?sensor3,?sensor4)";
                upHistoryData(sql, float.Parse(strings[0]), float.Parse(strings[1]), float.Parse(strings[2]), float.Parse(strings[3]), float.Parse(strings[4]));
            }
            
        }
        #endregion
        #region 历史数据
        private void ckBox_Save_CheckedChanged (object sender, EventArgs e)
        {
            if (IsSaveFlag != ckBox_Save.Checked)
            {
                IsSaveFlag = !IsSaveFlag;
            }

            if (IsSaveFlag)
            {
                ctxtMenStrip.Items[4].Text = "取消";
            }
            else
            {
                ctxtMenStrip.Items[4].Text = "保存";
            }
        }

        public void SaveData (string path)
        {
            string filePath = path;
            if (filePath == null)
            {
                filePath = DateTime.Now.ToString("HH_mm_ss") + ".txt";
            }
            else
            {
                filePath = path;
            }
            System.IO.DirectoryInfo DirInfo = new DirectoryInfo(filePath);
            DirInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
            System.IO.FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write);
            fileStream.Close();

        }
        private void Form1_FormClosed (object sender, FormClosedEventArgs e)
        {
            if (conn != null)
            {
                conn.Close();
            }
            
        }
        static string historyFile = "";
        static public List<List<float>> posHisSensorData = new List<List<float>>();
        static public List<float> tickTimeFloat = new List<float>();
        static public int dataNum = 0;
        static int totalSensors;
        int timeSpan = 1;
        static int j = 1;
        float rPosHis = 0;
        private void btOpenDataFile_Click (object sender, EventArgs e)
        {
            IsReadFlag = true;
            string current_day = DateTime.Now.ToString("MM_dd");
            string current_month = DateTime.Now.ToString("MM");
            string current_year = DateTime.Now.Year.ToString();

            Control.CheckForIllegalCrossThreadCalls = false;
            ChartTop();
            ChartBottom();
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Title = "请选择文件";
            dialog.InitialDirectory = xmlPath + "\\MeasureData" + "\\" + current_year + "\\" + current_month + "\\" + current_day;
            dialog.Filter = "所有文件(*.*) | *.*";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                historyFile = dialog.FileName;
                StreamReader sr = new StreamReader(historyFile, Encoding.UTF8);
                string line;
                string[] tempArr;
                tempArr = sr.ReadLine().Split('\t');
                if ("工件编号：".Equals(tempArr[0]))
                {
                    tb_wpID.Text = tempArr[1];
                }
                tempArr = sr.ReadLine().Split('\t');
                if ("工件名称：".Equals(tempArr[0]))
                {
                    strProjectInfo[1] = tempArr[1];
                }
                tempArr = sr.ReadLine().Split('\t');
                if ("环境温度(℃)：".Equals(tempArr[0]))
                {
                    strProjectInfo[2] = tempArr[1];
                }
                tempArr = sr.ReadLine().Split('\t');
                if ("工件温度(℃)：".Equals(tempArr[0]))
                {
                    strProjectInfo[3] = tempArr[1];
                }
                j = 1;
                tickTimeFloat.Clear();
                posHisSensorData.Clear();
                for (int i = 0; i < strSensorState.Count; i++)
                {
                    FigPanelsForTop[0].Charts[i].Series[0].Points.Clear();
                    FigPanel.ChartBot.Series[i].Points.Clear();

                    posHisSensorData.Add(new List<float>());

                }
                refreshResult();

                while ((line = sr.ReadLine()) != null)
                {
                    string[] strings = line.Split('\t');
                    totalSensors = strings.Length - 1;
                    for (int i = 0; i < totalSensors; i++)
                    {
                        if ("时间戳：".Equals(strings[0]))
                        {
                            strSensorState[i][1] = strings[i + 1];
                        }
                        else if ("测量结果：".Equals(strings[0]))
                        {
                            strSensorState[i][3] = strings[i + 1];
                        }
                        else if ("  合格：".Equals(strings[0]))
                        {
                            strSensorState[i][4] = strings[i + 1];
                        }
                        else if ("工件公差：".Equals(strings[0]))
                        {
                            floatSensorState[i][3] = float.Parse(strings[i + 1]);
                        }
                        else if ("传感器零点：".Equals(strings[0]))
                        {
                            floatSensorState[i][2] = float.Parse(strings[i + 1]);
                        }
                        else
                        {

                            posHisSensorData[i].Add(float.Parse(strings[i + 1]) - floatSensorState[i][2]);
                        }
                    }
                    int a;
                    if (int.TryParse(strings[0], out a))
                    {
                        tickTimeFloat.Add(float.Parse(strings[0]));
                        dataNum++;
                    }
                }
                tabControl1.SelectedTab = tabControl1.TabPages[0];
                cBox_fre.Text = Convert.ToString(floatSensorState[0][1]);
                tb_roomTempre.Text = strProjectInfo[2];
                tb_wpTempre.Text = strProjectInfo[3];
                if (IsSaveFlag)
                {
                    stopMeasure_Click(null, null);
                }
                
                testTimer.Start();
                ctxtMenStrip.Items[0].Enabled = false;
                ctxtMenStrip.Items[1].Text = "继续";
                ctxtMenStrip.Items[2].Enabled = true;
                ctxtMenStrip.Items[3].Enabled = true;
                ctxtMenStrip.Items[4].Enabled = false;
            }
            
        }
        private void testTimer_tick (object sender, EventArgs e)
        {
            timeSpan = (int)((tickTimeFloat[j] - tickTimeFloat[j - 1]) / 10000);
            testTimer.Interval = timeSpan;
            for (int i = 0; i < totalSensors; i++)
            {
                FigPanel.ChartBot.Series[i].Points.AddY(Convert.ToString(posHisSensorData[i][j]));
                FigPanelsForTop[0].Charts[i].Series[0].Points.AddY(posHisSensorData[i][j]);
                FigPanelsForTop[0].Charts[i].Titles[0].Font = new Font("微软雅黑", 22f);
                FigPanelsForTop[0].Charts[i].Titles[0].Text = strSensorState[i][0]
                    + "\r\n"
                    + strSensorState[i][2] + ":" + posHisSensorData[i][j - 1].ToString("0.0000") + "mm"
                    + "\r\n"
                    + "  测量结果:" + strSensorState[i][3] + "mm"
                    + "\r\n"
                    + "合格:" + strSensorState[i][4];
            }
            j++;
            if (j == tickTimeFloat.Count)
            {
                testTimer.Stop();
            }
        }
        #endregion
        #region 右键菜单
        private void refresh_Click (object sender, EventArgs e)
        {
            if (!IsReadFlag)
            {
                for (int i = 0; i < DlEn1.TotalSensors; i++)
                {
                    FigPanelsForTop[0].Charts[i].Series[0].Points.Clear();
                    FigPanel.ChartBot.Series[i].Points.Clear();
                }
                refreshResult();
            }
            else
            {
                for (int i = 0; i < totalSensors; i++)
                {
                    FigPanelsForTop[0].Charts[i].Series[0].Points.Clear();
                    FigPanel.ChartBot.Series[i].Points.Clear();
                }
                refreshResult();
            }
            
        }
        
        private void measure_Click (object sender, EventArgs e)
        {
            if (!IsReadFlag)//采集状态
            {
                if (IsSaveFlag)
                {
                    CreatTxtFile();
                    SaveData(dataPath);
                    CreatTable(strProjectInfo[4]);
                }
                ChartTop();
                ChartBottom();
                PosTimer.Interval = 1000 / int.Parse(cBox_fre.Text);
                StartTime = DateTime.Now;
                PosTimer.Start();
                bt_measure.Enabled = false;
                bt_stop.Enabled = true;
                ctxtMenStrip.Items[0].Enabled = true;
                ctxtMenStrip.Items[1].Enabled = false;
                ctxtMenStrip.Items[2].Enabled = true;
                ctxtMenStrip.Items[3].Enabled = true;
                if ("继续".Equals(ctxtMenStrip.Items[1].Text))
                {
                    ctxtMenStrip.Items[1].Text = "测量";
                }
                ckBox_Save.Enabled = false;
                ctxtMenStrip.Items[4].Enabled = false;
            }
            else//读历史数据状态
            {
                testTimer.Start();
                bt_stop.Enabled = true;
                ctxtMenStrip.Items[0].Enabled = false;
                ctxtMenStrip.Items[1].Enabled = false;
                ctxtMenStrip.Items[2].Enabled = true;
                ctxtMenStrip.Items[3].Enabled = true;
            }
            
        }
        private void suspend_Click (object sender, EventArgs e)
        {
            if (!IsReadFlag)//采集
            {
                PosTimer.Stop();
            }
            else//读历史数据
            {
                testTimer.Stop();   
            }
            bt_stop.Enabled = true;
            bt_measure.Enabled = true;
            ctxtMenStrip.Items[1].Enabled = true;
            ctxtMenStrip.Items[2].Enabled = false;
            bt_measure.Text = "继续";
            ctxtMenStrip.Items[1].Text = bt_measure.Text;
           
        }
       
        static string sqlMeasureResult;
        static string sqlMeasureGrade;
        private void stopMeasure_Click (object sender, EventArgs e)
        {
            if (!IsReadFlag)//采集
            {
                PosTimer.Stop();
                bt_stop.Enabled = false;
                bt_measure.Enabled = true;
                ckBox_Save.Enabled = true;
                ctxtMenStrip.Items[4].Enabled = true;
                string txtMeasureResult = "测量结果：";
                string txtMeasureGrade = "合格：";
                if (!ctxtMenStrip.Items[2].Enabled)//此时为暂停状态
                {
                    ctxtMenStrip.Items[0].Enabled = false;
                    ctxtMenStrip.Items[3].Enabled = false;
                }
                if (ctxtMenStrip.Items[2].Enabled)//此时为未暂停，直接从采集状态到停止状态
                {
                    ctxtMenStrip.Items[0].Enabled = false;
                    ctxtMenStrip.Items[1].Enabled = true;
                    ctxtMenStrip.Items[2].Enabled = false;
                    ctxtMenStrip.Items[3].Enabled = false;
                }
                /*if ("继续".Equals(ctxtMenStrip.Items[1].Text))
                {
                    ctxtMenStrip.Items[1].Text = "测量";
                    bt_measure.Text = "测量";
                }*/
                ctxtMenStrip.Items[1].Text = "测量";
                bt_measure.Text = "测量";
                for (int i = 0; i < DlEn1.TotalSensors; i++)
                {
                    FigPanelsForTop[0].Charts[i].Series[0].Points.Clear();
                    FigPanel.ChartBot.Series[i].Points.Clear();
                    txtMeasureResult += "\t" + strSensorState[i][3];
                    txtMeasureGrade += "\t" + Grade(i);
                    sqlMeasureResult += strSensorState[i][3] + "  ";
                    sqlMeasureGrade += Grade(i) + "  ";
                }
                uint uintWpID;
                if (IsSaveFlag)
                {
                    string strContent = File.ReadAllText(dataPath);
                    strContent = Regex.Replace(strContent, "测量结果：", txtMeasureResult);
                    strContent = Regex.Replace(strContent, "合格：", txtMeasureGrade);
                    File.WriteAllText(dataPath, strContent);
                    ProToMySql();

                    uintWpID = uint.Parse(strProjectInfo[4]);
                    uintWpID++;
                    strProjectInfo[4] = uintWpID.ToString();
                    tb_wpID.Text = strProjectInfo[4];
                    ModifyXmlInformation(sensorSetXml);
                }
                IsWriteFlag = false;
                sqlMeasureResult = null;
                sqlMeasureGrade = null;
                refreshResult();
            }
            else
            {
                testTimer.Stop();
                tickTimeFloat.Clear();
                posHisSensorData.Clear();
                ctxtMenStrip.Items[1].Enabled = false;
                ctxtMenStrip.Items[2].Enabled = false;
                refresh_Click(sender, new EventArgs());
                IsReadFlag = false;
            }
        }

        #endregion
        public string Grade (int i)
        {
            string grade ;
            float a = float.Parse(MeasureResult(i));
            if (floatCalculData[i].Count > 20)
            {
                if (Math.Abs(a) < floatSensorState[i][3])
                {
                    grade = "是";
                }
                else
                {
                    grade = "否";
                }
            }
            else
            {
                grade = "--";
            }
            return grade;
        }
        public string MeasureResult (int i)
        {
            string result;
            float a = 0;
            while (floatCalculData[i].Count > 2)
            {
                if ("位置度".Equals(strSensorState[i][2]))
                {
                    a = Difference(StaticMeasure(floatCalculData[i]));
                }
                if ("直线度".Equals(strSensorState[i][2]))
                {
                    a = Difference(StaticMeasure(floatCalculData[i]));
                }
                if ("平面度".Equals(strSensorState[i][2]))
                {
                    a = Difference(StaticMeasure(floatCalculData[i]));
                }
                if ("圆柱度".Equals(strSensorState[i][2]))
                {
                    a = Difference(StaticMeasure(floatCalculData[i])) ;
                }
                if ("同轴度".Equals(strSensorState[i][2]))
                {
                    a = Difference(StaticMeasure(floatCalculData[i])) ;
                }
                if ("径向圆跳动".Equals(strSensorState[i][2]))
                {
                    a = Difference(StaticMeasure(floatCalculData[i]));
                }
                if ("端面圆跳动".Equals(strSensorState[i][2]))
                {
                    a = Difference(StaticMeasure(floatCalculData[i]));
                }
                if ("径向全跳动".Equals(strSensorState[i][2]))
                {
                    a = Difference(StaticMeasure(floatCalculData[i]));
                }
                break;
            }
            result=a.ToString("0.0000");
            return result;
        }
        float Difference (List<float> floats)
        {

            List<float> result;
            float difResult;
            result = floats;
            float tempMax = 0;
            float tempMin = 0;
            foreach (float item in result)
            {
                tempMax = tempMax >= item ? tempMax : item;
                tempMin = tempMin <= item ? tempMin : item;
            }
            float tempDif = Math.Abs(tempMax) - Math.Abs(tempMin);
            if (tempMin == tempMax)
            {
                difResult = tempMax;
                
            }
            else
            {
                if (tempMin >= 0)
                {
                    difResult = tempMax - tempMin;
                    
                }
                else if (tempMax <= 0)
                {
                    difResult = tempMin - tempMax;
                    
                }
                else
                {
                    if (tempDif >= 0)
                    {
                        difResult = tempMax - tempMin;
                    }
                    else
                    {
                        difResult = tempMin - tempMax;
                    }
                }
            }
            return difResult;
        }
        public List<float> StaticMeasure (List<float> floats)
        {
            
            List<float> result= new List<float>();
            if(floats.Count > 40)
            {
                result=floats.GetRange(20,floats.Count-40);//掐头去尾
            }
            return result;
        }
        void refreshResult ()
        {
            if(!IsReadFlag)
            {
                for (int i = 0; i < DlEn1.TotalSensors; i++)
                {
                    floatMeasureData[i].Clear();
                    floatCalculData[i].Clear();
                    FigPanelsForTop[0].Charts[i].Titles[0].Font = new Font("微软雅黑", 22f);
                    FigPanelsForTop[0].Charts[i].Titles[0].Text = strSensorState[i][0]
                        + "\r\n"
                        + strSensorState[i][2] + ":" + "0.0000" + "mm"
                        + "\r\n"
                        + "  测量结果:" + "0.0000" + "mm"
                        + "\r\n"
                        + "合格:" + "--";
                }
            }
            else
            {
                for (int i = 0; i < totalSensors; i++)
                {
                    floatMeasureData[i].Clear();
                    floatCalculData[i].Clear();
                    FigPanelsForTop[0].Charts[i].Titles[0].Font = new Font("微软雅黑", 22f);
                    FigPanelsForTop[0].Charts[i].Titles[0].Text = strSensorState[i][0]
                        + "\r\n"
                        + strSensorState[i][2] + ":" + "0.0000" + "mm"
                        + "\r\n"
                        + "  测量结果:" + "0.0000" + "mm"
                        + "\r\n"
                        + "合格:" + "--";
                }
            }
            


         
        }

        private void cBox_fre_SelectedIndexChanged (object sender, EventArgs e)
        {
            for(int i = 0;i< DlEn1.TotalSensors; i++)
            {
                floatSensorState[i][1] = float.Parse(cBox_fre.Text);
            }
            
        }

        private void tb_roomTempre_TextChanged (object sender, EventArgs e)
        {
            strProjectInfo[2] = tb_roomTempre.Text;
        }

        private void tb_wpTempre_TextChanged (object sender, EventArgs e)
        {
            strProjectInfo[3] = tb_wpTempre.Text;
        }

        private void 保存ToolStripMenuItem_Click (object sender, EventArgs e)
        {
            IsSaveFlag = !IsSaveFlag;
            //ckBox_Save.Checked=!ckBox_Save.Checked;
            if(IsSaveFlag)
            {
                ctxtMenStrip.Items[4].Text = "取消";
                ckBox_Save.Checked = true;
            }
            else
            {
                ctxtMenStrip.Items[4].Text = "保存";
                ckBox_Save.Checked = false;
            }
        }
        static MySqlConnection conn;
        public void ConnectMysql ()
        {
            string connStr = "server=localhost;User Id=root;password=password123;Database=demo";
            conn= new MySqlConnection(connStr);
            conn.Open ();
            if(conn.State== System.Data.ConnectionState.Open)
            {
                mysqlState.BackColor = Color.Green;
            }
        }
        //创建表
        public void CreatTable (string str)
        {
            string creatTableQuery = $@"CREATE TABLE `{str}` (
                                    `id` INT(11) NOT NULL AUTO_INCREMENT,
                                    `timestp` FLOAT NULL,
                                    `sensor1` FLOAT NULL,
                                    `sensor2` FLOAT NULL,
                                    `sensor3` FLOAT NULL,
                                    `sensor4` FLOAT NULL,
                                    PRIMARY KEY (`id`)
                                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
            MySqlCommand command = new MySqlCommand(creatTableQuery, conn);
            command.ExecuteNonQuery();
        }
        //上传数据到表中
        public void ProToMySql ()
        {
            string sql = "insert into demo.measinfo (time,wpID, measureResult,measureGrade,wpTemp, roomTemp) " +
                 "values(?time,?wpID,?measureResult,?measureGrade,?wpTemp,?roomTemp)";
            upFile(sql, current_time,strProjectInfo[4], sqlMeasureResult, sqlMeasureGrade, strProjectInfo[3], strProjectInfo[2]);


        }
        public int upFile(String sql,string time,string wpID, string measureResult, string measureGrade, string wpTemp, string roomTemp)
        {
            if(conn!= null)
            {
                MySqlCommand cmd = new MySqlCommand();
                cmd.CommandText = sql;
                cmd.CommandType = CommandType.Text;

                cmd.Parameters.Add("@time", MySql.Data.MySqlClient.MySqlDbType.VarChar);
                cmd.Parameters.Add("@wpID",MySql.Data.MySqlClient.MySqlDbType.VarChar);
                cmd.Parameters.Add("@measureResult", MySql.Data.MySqlClient.MySqlDbType.VarChar);
                cmd.Parameters.Add("@measureGrade", MySql.Data.MySqlClient.MySqlDbType.VarChar);
                cmd.Parameters.Add("@wpTemp", MySql.Data.MySqlClient.MySqlDbType.VarChar);
                cmd.Parameters.Add("@roomTemp", MySql.Data.MySqlClient.MySqlDbType.VarChar);

                cmd.Parameters[0].Value = time;
                cmd.Parameters[1].Value = wpID;
                cmd.Parameters[2].Value = measureResult;
                cmd.Parameters[3].Value = measureGrade;
                cmd.Parameters[4].Value = wpTemp;
                cmd.Parameters[5].Value = roomTemp;
               
                

                cmd.Connection= conn;
                return cmd.ExecuteNonQuery();
            }
            return 0;
        }
        public int upHistoryData (string sql,float timestp,float sensor1,float sensor2,float sensor3,float sensor4 )
        {
            if (conn != null)
            {
                MySqlCommand cmd = new MySqlCommand();
                cmd.CommandText = sql;
                cmd.CommandType = CommandType.Text;

                //cmd.Parameters.Add("@wpID", MySql.Data.MySqlClient.MySqlDbType.VarChar);
                cmd.Parameters.Add("@timestp", MySql.Data.MySqlClient.MySqlDbType.Float);
                cmd.Parameters.Add("@sensor1", MySql.Data.MySqlClient.MySqlDbType.Float);
                cmd.Parameters.Add("@sensor2", MySql.Data.MySqlClient.MySqlDbType.Float);
                cmd.Parameters.Add("@sensor3", MySql.Data.MySqlClient.MySqlDbType.Float);
                cmd.Parameters.Add("@sensor4", MySql.Data.MySqlClient.MySqlDbType.Float);

                //cmd.Parameters[0].Value = wpID;
                cmd.Parameters[0].Value = timestp;
                cmd.Parameters[1].Value = sensor1;
                cmd.Parameters[2].Value = sensor2;
                cmd.Parameters[3].Value = sensor3;
                cmd.Parameters[4].Value = sensor4;
                cmd.Connection = conn;
                return cmd.ExecuteNonQuery();

            }
            return 0;
        }

        private void splitContainer4_Panel2_Paint (object sender, PaintEventArgs e)
        {

        }

        private void tb_wpID_TextChanged (object sender, EventArgs e)
        {
            strProjectInfo[4] = tb_wpID.Text;  
        }

        
    }
}
